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.
Related
I'm trying to figure out a way to ensure the user enters valid input for a personal website project i'm doing. I've been searching for ways to do this for a little while now, but i'm coming up short. In C++, or most other languages I assume, this would be rather simple. For example,
string example;
cout << "Enter a number less than 100\n";
cin >> example;
while(example > 100){
cin >> example;
}
This would ensure the user only enters valid information.
With my Javascript/HTML code, i'm getting the initial user input like so,
<input id = "example" type="text" placeholder="Enter Here" onchange="foo()">
Then in the javascript file, I first attempted to just put an alert inside a while loop, but that doesn't allow the user to input new information since javascript continues on to the next function/part of the code regardless.
I then tried adding an event listener, but i'm still not sure how I get the code to pause at that point to ensure the user enters valid information before moving on.
Any help would be appreciated.
You don't use loops for this in JavaScript, because the loop can't stop to wait for the user to fill in a field.
Instead, you check whether the ending condition is met in the function that runs when the user enters input into the field. This is the foo() function.
let input = document.getElementById("example");
let output = document.getElementById("output");
let message = document.getElementById("prompt");
function foo() {
let value = parseInt(input.value);
if (value > 100) {
message.classList.add("error");
input.focus();
} else {
output.innerText = "Congratulations, you win!";
input.style.display="none";
message.classList.remove("error");
}
}
.error {
color: red;
}
<div id="prompt">Please enter a number below 100:</div>
<input id="example" type="text" placeholder="Enter Here" onchange="foo()">
<div id="output"></div>
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 ;
So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. I also had a submit function that sends an email through the server. Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.
So I did the following but can't get it to work:
<script>
function validate(){
var phone=/[0-9]*/;
var x=document.forms["form"]["contactnum"].value;
if (x!=phone){
alert("Contact Number must be a valid phone number (no dashes)");
return false;
}
else {
alert("Thank you! We have received your information and will contact you shortly.");
ajax('{{=URL('new_post')}}',['phone'], 'target');
return false;
}
}
</script>
The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. If I try to match it with any other var it will always say I'm not matching the [0-9]*. I already have written several complex regex's but really don't want to use anything on this simple form. I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null. I don't even care if they put in a "2" for the phone, just so long as it's a digit.
Thanks.
if ( x.match(/^[0-9]+$/) ) {
// valid
} else {
// invalid
}
That's not how you use a regular expression:
if (!phone.test(x)) ...
Also if you want to match a string with nothing but digits, try
var phone = /^\d*$/;
That will match the empty string too; use + instead of * if you want at least one digit.
You actually seem to have two questions in one here. For the first part, you haven't shown how you're using validate(), but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. For example, the following will not work:
$('#myform').submit(function(){
validate();
});
But this would successfully stop the default submit process:
$('#myform').submit(function(){
return validate();
});
validate() would return false, and then your handler returns the same.
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.
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
}