I have a use case where I want to add multiple email addresses in the sap.m.Input field. Is there any way I can do it with keeping type sap.m.InputType.Email of the input field?
I have checked that in HTML5, <input> tag has multiple attribute which allows user to enter multiple values of the given input-type. I want similar thing here.
I want to validate all the email addresses also. So currently I am doing it by splitting the email addresses from the sap.m.Input value by semicolons and manually validating each email address from the sap.m.Input's email validator.
var oEmails = new sap.m.Input();
onFormSubmit: function(oEmail) {
var isValidEmails = false;
var emails = oEmail.getValue().split(";");
for (var i=0; i<emails.length; i++) {
var emailValidation = oEmail.getValidator().emailValidation(emails[i]);
var isInvalidEmail = (emailValidation.valueType === "Error");
if (isInvalidEmail) {
showError(oEmail);
isValidEmails = false;
break;
} else {
isValidEmails = true;
}
}
return isValidEmails;
}
I haven't added type of Input in the oEmails as it return an error for multiple emails. But I want to use it so Input control should take care of the validation. Is there any better approach to deal with these problem?
Thanks in advance.
Have you looked at sap.m.MultiInput? It uses tokens for the individual entries but semantically it offers you to enter multiple entries and you can set the type to email, although I have not tried it so far.
Related
hopefully that makes sense.... basically I have a form and want to take the input for the "email" field and truncate/trim the value before the "#" symbol and give that value to another hidden field.
EDIT/ADDED: Also, if possible in the same function, it would be great to automatically generate and append a random number (between 01 and 99 would suffice) to ensure there are no "duplicates/matching "hiddenfield" values... for example if the email address is something nondescript like info#blahblah.com, where "info" might be blocked if already in system but info46 and info07 would be fine.
IF it is not appropriate to add to the question like this I apologize and will edit it out, mark the question as answered based on original criteria and open a new question that hopefully can add to this.
So basically if someone entered "JohnSmith#hotmail.com", "JohnSmith26" (as an example) would be assigned as the value for another hidden form field.
example:
<label>Email Address:</label><input type="text" id="email" name="email" value="" size="30" maxlength="80"/>
<input type="hidden" id="hiddenfield" name="hiddenfield" value="truncated email" />
I saw this thread but am not using coldfusion etc and am hoping to just find a simple way to do similar within the form: how do I trim an email input address so only the data before the # is inputted into the database?
am looking for the best way using javascript/jQuery to assign the truncated value to the other field.
You probably want something like this
Javascript
var email = document.getElementById("email"),
hidden = document.getElementById("hiddenfield");
function transferTruncated() {
var target = this,
name;
if (target.value.indexOf("#") !== -1) {
name = target.value.split("#")[0].trim();
if (name && name.search(/\s/) === -1) {
hidden.value = name;
} else {
hidden.value = "truncated email";
}
} else {
hidden.value = "truncated email";
}
}
email.addEventListener("change", transferTruncated, false);
On jsfiddle
Note: I removed the hidden type from the input field so that you can see it, and you may want to check that the name is further valid too before assigning it.
First split the email address, then use regex to remove white spaces and then assign it to the hidden field.
var email = document.getElementById('email').value.split('#')[0],
hidden = document.getElementById('hiddenfield'),
trimmedValue = email.replace(/\s+/g, '');
hidden.value = trimmedValue ;
I have a textarea that contains multiple email addresses with a ; separated delimiter. We have a requirement to highlight invalid email addresses red using JavaScript or jQuery.
For example: I have 10 email addresses separated by commas in the textarea and 3 are invalid so these email addresses should be highlighted red and the user will be able to identify invalid email-addresses easily.
See the following jsFiddle for a working example.
As others have said, you cannot do this with a Textarea. However, you can create a div, style it to look like your other form elements, and set the ContentEditable property to True. With a bit of Javascript, you'll have exactly what you're looking for.
The following code will loop through the list of semi-colon delimited email addresses and use regex to test each address. If there is no match, the text is wrapped in a span and assigned a "red" class. The resulting new HTML is then applied to the contenteditable div and users will see the invalid email addreses highlighted
JS
$('#btnSubmit').click(function() {
var textEntered = $('#divEdit').text();
var textResult = [];
$.each(textEntered.split(';'), function(index, item) {
if (item.match(/^\S+#\S+\.\S+$/)) {
textResult.push(item);
}
else {
textResult.push('<span class="red">' + item + '</span>');
}
});
$('#divEdit').html(textResult.join(';'));
});
When a user submits the form, all you need to do is get the HTML of the contenteditable div and strip out and HTML and you'll be left with only the text of the entered email address.
Note: There are many challenges in trying to uses regex to validate email address (Using a regular expression to validate an email address). Be careful in what you're trying to achieve.
Agreeing with the comments that the question is lacking much necessary information, there are some possible options depending on the need and scope. Here is an example that demonstrates 2 options: either split the valid and invalid email addresses into 2 different text areas, or use a div to display the result and hide the textarea form controls. Again, without knowing anything about where the list is coming from, how it's being validated, etc, this is just a stab:
Good luck
HTML
<form name="test" id="test">
<textarea name="valid" id="valid"></textarea><br />
<textarea name="invalid" id="invalid" style="color:red;"></textarea>
</form>
<div id="ta_sudo"></div>
SCRIPT
function processEmailAddresses(){
var addList = 'abc#123.com;www#www.com;t#d.cor;t.dd.www';
separateInvalid(addList);
}
function separateInvalid(addList){
var addArr = addList.split(';');
var validArr = [];
var invalidArr = [];
var compositeArr = [];
for(var i = 0; i < addArr.length; i++){
if(!testEmail(addArr[i])){
invalidArr.push(addArr[i]);
compositeArr.push('<span style="color:red">' + addArr[i]) + '</span>';
}else{
validArr.push(addArr[i]);
compositeArr.push(addArr[i]);
}
}
$('#valid').val(validArr.join(';'));
$('#invalid').val(invalidArr.join(';'));
$('#ta_sudo').html(compositeArr.join(';'))
}
function testEmail(emailAddress){
var regexEmail = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
return regexEmail.test(emailAddress);
}
processEmailAddresses();
What would a JavaScript script be that, on submit, gets all form elements with class="required" and if they're empty, displays an alert box, "you must fill out so-and-so"?
I was thinking of an if-else, and in the if section we would get a while that loops through all the class=required elements, and the else would submit the form.
There are many many JavaScript libraries on the internet that do exactly this.
Try this one:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Or try a Google search for JavaScript Form Validation.
It is fairly easy to loop over the elements of a form and check that those with a certain class have a value that meets certain criteria:
<form name="f0" onsubmit="return validate(this);">
<input name="inp0" class="required" >
<input name="inp2" class="required" >
<input type="submit">
</form>
<script type="text/javascript">
var validate = (function() {
var reClass = /(^|\s)required(\s|$)/; // Field is required
var reValue = /^\s*$/; // Match all whitespace
return function (form) {
var elements = form.elements;
var el;
for (var i=0, iLen=elements.length; i<iLen; i++) {
el = elements[i];
if (reClass.test(el.className) && reValue.test(el.value)) {
// Required field has no value or only whitespace
// Advise user to fix
alert('please fix ' + el.name);
return false;
}
}
}
}());
</script>
The above is just an example to show the strategy.
Using an alert is less than optimal, usually an area is set aside adjacent to the required fields so that error messages can be written there to direct the user's attention to the invalid fields. You can also set all the error messages in one go, then return, rather than one at a time.
Edit—updating multiple errors
Have an element adjacent to each control to be validated with an id like the element's, so if an input is called firstName, the error element might have an id of firstName-err. When an error is found, it's easy to get the related element and put a message in it.
To do all at once, use a flag to remember if there are any errors, say "isValid" that is set to true by default. If you find any errors, set it to false. Then return it at the end.
Using the example above, the HTML might look like:
<input name="firstName" class="required" >
<span id="firstName-err" class="errMsg"></span>
Errors for firstName will be written to firstName-err.
In the script, if an error is found:
// At the top
var isValid = true;
var errEl;
...
// When entering the for loop
el = elements[i];
errEl = document.getElementById(el.name + '-err');
// when error found
isValid = false;
if (errEl) errEl.innerHTML = '... error message ...';
// else if error not found
// remove message whether there is one or not
if (errEl) errEl.innerHTML = '';
...
// At the end
return isValid;
You can also use a popup to show the errors, however that is really annoying and the users must dismiss the popup to fix the errors. Much better to just write next to each one what is wrong and let the user fix things in their own time.
I have a form which has 4 columns and the user can dynamically add or delete rows.
Now I tried to validate this through javascript following code:-
<script type="text/javascript">
function chkempty()
{
var x=document.forms["main"]["qty[]"].value
var y=document.forms["main"]["price[]"].value
var z=document.forms["main"]["item[]"].value
if (x==null || x=="") {
alert("Quantity must be filled out");
return false;
}
if (y==null || y=="") {
alert("Price must be filled out");
return false;
}
if (z==null || z=="") {
alert("Itemcode cannot be empty");
return false;
}
}
It works for the first row but when the user selects more than one row, even after filling up values, he is getting the validation error message. can someone help me with this please?
Thanks and keep smiling.
VERY simple solution here:
Use Jquery Inline Validator
When you add new lines of content to the table, simply ensure that you have the proper class defined (such as class="validate[required,custom[email]]" ) to ensure that it will validate the field correctly as you wish. I often just do the required element, but the example I gave above also does email format checking. There are additional built in checkers for phone numbers, currency, etc.
If the user messes up an input, it will display a visually appealing tooltip like dialog next to the field with the error.
Done. Simple. Clean. Fast.
None of these solutions make up for the fact that you really need to sanitize on the server-side as well. Any Javascript can be bypassed, so it's not 100% guaranteed to be safe or accurate. But it is a good start and provides quality, instant feedback to the user.
var x=document.forms["main"]["qty[]"].value
You should loop over the elements and validate each value, instead of trying to get a value from an array, I guess.
var x=document.forms["main"]["qty"];
for ( var i=0, len=x.length; i<len; ++i ){
// validate the value of the current element.
}
EDIT: added a small example.
document.forms.form_id.control_name will return either an HTMLElementNode or a NodeList depending if there are one or many matching elements.
You can do something like:
var x=document.forms["main"]["qty[]"]
if (x.nodeName) {
// Is a Node. Work with its value
} else {
// Is a NodeList, loop over it with for
for (var i = 0; i < x.length; i++) {
var node = x[i];
// Work with its value
}
}
On a form, I need to make sure that all fields are filled in and that the phone # and email address are valid. I tried using a jQuery validation plugin but it changed the page's look and feel. The plugin also was dynamically looking for some css files in some spot that was unexpected.
I love jQuery but the plugin seemed too much for what I wanted.
Since all I need to do is to make sure the fields are not empty and that the phone number is valid and email is valid, what javascript functions do you suggest? I will still use jQuery core.
Serverside we want to use apache commons PhoneNumberFormatter and same with email validation.
Thanks!
I think you're looking for JavaScript regular expressions, using the RegExp object that comes as a standard part of JavaScript. You can use that to perform basic checking of email addresses and phone numbers.
e.g.
function emailIsValid(emailAddress) {
var emailRegex = /\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/;
return !!emailAddress.match(emailRegex);
}
The code above is not tested, but it should give you an idea of how to do it. Just do the same again for the telephone number, and then do something like this:
if (emailIsValid(emailAddressValue) && telephoneNumberIsValid(telephoneValue)) {
//Submit form
} else {
alert ("There are errors on the form, please correct and invalid data");
}
In this jsfiddle you'll find a JQueryless method I use to check form fields. It checks all form fields periodically using an interval function.
Everyone focused on the email and phone number validation, but encase you need help with detecting empty text boxes and even just how/when to call the code for email/phone validation:
<script type="text/javascript">
function validate()
{
var curVal;
for(var index = 1 ; index < 15 ; index++)
{
curVal = document.getElementById("textbox_"+index).value
if(curVal == "")
{
alert("empty text box")
return(false); //false will stop the form from submitting
}
if(index = 5)// email text box
{
//validate email
}
}
}
</script>
<type="input" id="textbox_1">
<type="submit" value="Submit" onClick="validate()">
here is one for email
function checkemail()
{
var str=email
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z] {2})?)$/i
if (filter.test(str))
testresults=true
else
{
alert("Please input a valid email address!")
testresults=false
}