I have four text fields with labels name, age, city and phone number.I have to validate it if it left empty. it should alert me to fill. How to validate a text field with required field validator in sapui5?
问题:
回答1:
You can simply write a function that get the textfields and checks their value.
This could look like this:
function validateTextFieldValues() {
// this function gets the first textfield
var nameTextField = sap.ui.getCore().byId("idOfTheTextFieldContaingTheName");
//this function checks its value, you can insert more checks on the value
if(nameTextField.getValue() === "") {
alert("Please enter a name.");
}
// ...
// the same for the other fields
}
Then you can bind the function on the button-click, for example when creating the button:
new sap.ui.commons.Button({
// your buttonconfiguration
click: function(){
validateTextFieldValues();
}
});
Additionally the TextField
has an attribute called valueState
.
In connection with its event liveChange
there is the opportunity to validate the input while typing:
new sap.ui.commons.TextField({
// your configuration
liveChange: function(){
if(this.getValue() === "")
this.setValueState(sap.ui.core.ValueState.Error);
else
this.setValueState(sap.ui.core.ValueState.Success);
}
});
(https://openui5.hana.ondemand.com/docs/api/symbols/sap.ui.core.ValueState.html)
回答2:
You can validate it on change of the field value itself as below
var oname = new sap.ui.commons.TextField({
id: 'input2',
change : function(){
if(this.getValue()=='')
alert("enter some value");
}
});
Or you can write a function for validation on click of some button.
回答3:
Even using the required property will not help as UI5 does not puts any controls in forms tags. The required property sets an attribute
aria-required=true
You can use jQuery to select all the aria-required elements and process them on any other controls event say press of button.
Below is sample code for the same.
var oBtn = new sap.ui.commons.Button();
oBtn.attachPress(function(){
var error;
jQuery('input[aria-required=true]').each(function(){
var oInput = sap.ui.getCore().byId(this.id);
var val = oInput.getValue();
if(!val){
var sHtml = '<ul><li><strong> value is empty</li></ul>';
var sValueState = '<strong>Error!</strong>';
// Combine Input value, Error title and message into a Rich Tooltip
var oTooltip = new sap.ui.commons.RichTooltip({ text: sHtml, valueStateText: sValueState});
oInput.setTooltip(oTooltip);
oInput.setValueState(sap.ui.core.ValueState.Error);
error = false;
}else{
oInput.setValueState(sap.ui.core.ValueState.None);
oInput.setTooltip(' ');
}
});
if(error){
return error;
}
});