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 ;
Related
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.
Need help getting this function to:
Validate data format
Validate data is existing
Focus on missing fields (One at a time is fine)
The function below is updated from some advice. It works much better then my original. Problem though is if email field is blank it works great, wont move on until value is put in. But the other fields will focus correctly, but still allow the func to move to else, which just lowers opacity as you can see.
function quantity_box() {
// store all your field names in an array
var fieldNames = ["EMAIL", "BILLTOFIRSTNAME", "BILLTOLASTNAME"];
// loop over each field name in that array
for (var i = 0; i < fieldNames.length; i++) {
// extract the field name
var fieldName = fieldNames[i];
// use the field name to index the form object and get the field itself
var field = document.forms["billing_form_id"][fieldName];
// check the field's value to see if it's empty
if (field.value === '') {
field.focus();
// break from our loop, since we've already found an invalid value
break;
}else{
$(".prod_billing_box").delay(0).animate({"opacity": "0"}, 200);
$(".prod_quantity_box").delay(215).animate({"opacity": "1"}, 200);
}
}
Also a note. Even though fields like EMAIL have settings like TextMode="Email" to verify proper format, the above function also ignores that.
You've misunderstood how indexes work. The following line is valid, but not doing what you expect it to.
["EMAIL" && "BILLTOFIRSTNAME" && "BILLTOLASTNAME"]
What this is actually doing is performing a boolean expression using and operations, like you would in an if statement. If you actually run that line in your javascript console, it will print out
"BILLTOLASTNAME"
Which is still valid, but not what you want.
Instead, you need to loop over all the form fields and check each one to make sure it's valid. If any of the fields are invalid, you can break out of the loop.
// track if the entire form is valid, start true
var allValid = true;
// store all your field names in an array
var fieldNames = ["EMAIL", "BILLTOFIRSTNAME", "BILLTOLASTNAME"];
// loop over each field name in that array
for (var i = 0; i < fieldNames.length; i++) {
// extract the field name
var fieldName = fieldNames[i];
// use the field name to index the form object and get the field itself
var field = document.forms["billing_form_id"][fieldName];
// check the field's value to see if it's empty
if (field.value === '') {
field.focus();
// our entire form isn't valid
allValid = false;
// break from our loop, since we've already found an invalid value
break;
}
}
// if we make it this far and allValid is still true...
if (allValid) {
// perform your "else" code here
}
One possibility worth noting is that all of this can be done with no javascript whatsoever using HTML5 form field validators. As long as you wrote your form fields in a <form> tag, you can add validators such as required to a field and the form will not submit, as well as display validation warnings, until the validators all pass. Below is a working example.
<form>
<input type="text" required placeholder="Must fill me in"><br/>
<input type="checkbox" required> Must be checked<br/>
<input type="radio" name="radiogroup" required> One must be chosen<br/>
<input type="radio" name="radiogroup"> One must be chosen 2<br/>
<input type="email" placeholder="Must be an email if filled"><br/>
<br/>
<button type="submit">Submit</button>
</form>
It's also possible to query the form element itself and as it if it's valid, as well as use :valid CSS form selectors to style valid and invalid fields.
How can I set html input to accept only numbers and email Id?
<input id="input" type="text" />
As mentioned above in the comments, this should work if you want to accept both 8-digit phone numbers and email addresses:
HTML form code:
<form onsubmit="return validateInput()">
<input type="text" name"mail_or_phone"/>
</form>
JS validation:
function validateInput()
{
var fieldValue= document.getElementById("mail_or_phone").value;
// taken from this SO post: http://stackoverflow.com/questions/7126345/regular-expression-to-require-10-digits-without-considering-spaces
var phoneValidation= /^([\s\(\)\-]*\d[\s\(\)\-]*){8}$/;
var mailValidation= /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (fieldValue.match(phoneValidation)) {
// correct phone structure
return true;
} else if (fieldValue.match(mailValidation)) {
// correct mail format
return true;
} else {
// incorrect structure
return false;
}
}
Here's a fiddle showing an example of the above code. In case of an incorrect answer you should show some kind of warning (not included in the code).
You can set input to type="email" and type="tel".
<input id="input" type="number" />
<input id="input" type="email" />
Check this info out on w3schools
... I see you want the same input, so you would stick with text then check the input using regex
\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}\b.
then whatever regex you need to validate your number
You can run a simple regex against the phone number and the email. That will most likely not catch all issues but it will give you a starting point.
Pseudo code:
//if input is phone
// do something
// else if input is email
// do something else
// else (when it is neither)
// throw an error
or you can even shorten this
// if input is phone or input is email
// do something
//else
//trow error
You can find a ton of regex solutions in the library at regex101.com. There is a whole bunch of email and phone number validators.
One that is supposed to check both (and I didn't look to deeply into the regex) is: \(^\+[0-9]{9,15}$)|(^.+#.+\..+$)\i
This should be true if the input string is a phone or email. However, like I said above, it most likely needs refinement.
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.