Validate Forms using Javascript on the email input field - javascript

Please i am trying to specify a pattern in the email input field in my form that it takes on lowercase words and if uppercase words are inputted in the email field it give an error and the form isn't submitted.

You can try this with javascript.
function checkText(e) {
const text = e.target.value;
if (text && (text === text.toUpperCase() || text.substr(-1) === text.substr(-1).toUpperCase()))
console.log('No upper case allowed')
}
<input type="text" oninput="checkText(event)">
Working FIddle

Related

How to prevent the user from entering the character "`" in the Input field?

<input class="name-input" type="text"/>
I assume that there is some kind of regular expression to solve this problem, but I could not find on the Internet which one..
I will be very grateful if you help =')
Updated: the main question is how to prevent the user from entering the character "`" in the Input field. I don't understand hot to do this.
You can add an eventlistener to the input field and check for any charachter, that you don't want for each keystroke.
I made a quick demo: https://codesandbox.io/s/vigilant-leaf-h2syxv?file=/index.html:115-160
let item = document.querySelector(".name-input");
item.addEventListener("keypress", (e) => {
if (e.key === "~" || e.key === "`") {
e.preventDefault();
}
});
<input class="name-input" type="text" />
So you should start by making a list of the special characters that you would to prevent users from using them, i assume that your list contains : [~,',",(,),`].
Then you can use this :
let name = document.querySelector('.name-input')
let regex = "[`'"()~]"
if ( name.match(regex) ){
console.log('There was a match');
} else {
console.log('NO match');
}

Why HTML5 input type email doesn't allow empty space?

I use input type=email in my application. Prior to that in the old system developers user input type=text. Recently I was asked to fix the 'issue' in my code. The problem was reported by user when entering email address in the input field, accidentally empty space was entered on the end. Then user tried to Save the form, and error message was displayed under the email field This field is mistyped. I'm wondering if this is the way type=email should work and prevent empty space in the email address fields?
I tested this problem in Chrome and empty space will not be detected, but in Firefox will be and error message will show up.
$("#save").on("click", function() {
console.log(verifyFields('my-form'));
if (verifyFields('my-form')) {
alert('Saved!');
}
});
function verifyFields(containerID, includeInvisible) {
includeInvisible = includeInvisible || false;
let isValid = true;
const hdlMap = {
//'valueMissing': "This field is required",
//'patternMismatch': "This field is invalid",
'tooLong': "This field is too long",
'rangeOverflow': "This field is greater than allowed maximum",
'rangeUnderflow': "This field is less than allowed minimum",
'typeMismatch': "This field is mistyped"
};
const arrV = Object.keys(hdlMap);
const invalidInputs = [];
$("#" + containerID).find("input,textarea,select").each(function() {
var curItem$ = $(this);
var errMsg = [];
var dispfld = curItem$.data("dispfld");
var label = curItem$.data("label");
if (includeInvisible || curItem$.is(":visible")) {
if (curItem$[0].validity.valid) {
curItem$.removeClass("is-invalid");
return;
}
if (curItem$[0].validity['valueMissing']) {
var reqMsg = label ? label + " field is required" : "This field is required";
errMsg.push(reqMsg);
}
if (curItem$[0].validity['customError'] && dispfld) {
errMsg.push(dispfld);
}
if (curItem$[0].validity['patternMismatch'] && dispfld) {
errMsg.push(dispfld);
}
arrV.forEach(function(prop) {
if (curItem$[0].validity[prop]) {
errMsg.push(hdlMap[prop]);
}
});
if (errMsg.length) {
if (!curItem$.next().is(".invalid-feedback")) {
curItem$.after('<div class="invalid-feedback"></div>');
}
curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
invalidInputs.push(curItem$);
isValid = false;
} else {
curItem$.removeClass("is-invalid");
}
}
});
if (invalidInputs.length) {
invalidInputs[0].focus();
}
return isValid;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="my-form" id="my-form">
<input type="email" name="user-email" id="user-email" required>
<button type="button" id="save">Save</button>
</form>
a space isn't a valid character for an input type="email" because we can't have email addresses with spaces in them (A).
So in this case you have an unfortunate scenario where the space isn't in the middle of the email address, but at the beginning or end. But if you look at the validation that the browser follows for this input type, it still won't be allowed.
You have two options:
Set it back to input type="text", but set the same validation pattern that applies for emails: <input type="text" pattern="/^[a-zA-Z0-9.!#$%&'*+\/=?^_{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" /> and then modify that regex to allow for ending spaces (though you need to check on the back-end to make sure it will allow them, or otherwise you need to do a .trim() to remove those surrounding spaces.
Do a .trim() on your input after the user exits the input; removing whitespaces at the start or end.
(A) According to this answer:
space and "(),:;<>#[] characters are allowed with restrictions (they are only allowed inside a quoted string...

Input validation (JavaScript) using required attribute

I have a problem with input validation using pattern and required attribute. The idea is that I want to use my own title, not the browser's. When I want to complete the input with characters that not correspond with the regex (numbers), message 'Only letters allowed' displays near the input. But when I complete with letters it shows me the same message that my characters are incorrect. Who knows what is the problem? Thank you.
<script type="text/javascript">
function validation (textbox) {
var regex = /^[a-zA-Z]+$/;
if (textbox.value == '') {
textbox.setCustomValidity('Required field');
}
else if(!regex.test(textbox.value)){
textbox.setCustomValidity('Only letters allowed');
}
else {
textbox.setCustomValidity('');
}
return true;
}
FORM input:
<input type="text" id="first-name" name="first_name" placeholder="First Name" oninvalid="validation(this);" required="requied" pattern="/^[a-zA-Z]+$/"/>

Validation issue with condition

I am new with JavaScript validation and learning I am trying to validate form but I am getting issue with condition.
In my form I have one field which is name and one submit button.
What I am trying is:
If user click to to submit button and text box is empty give alert('Please enter your First Name.')
Then If user entered value which is not allowed by regex give alert('Please enter only letters no special character allowed.');
but I am getting first alert every time. Whats wrong i don't understand.
My Code:
jQuery('#send').click(function () {
var reg_first_name = /^[A-Za-z ]{3,20}$/;
var first_name = jQuery('#sa_first_name').val();
if(first_name.length > 0){
alert('Please enter your First Name.');
document.getElementById("sa_first_name").focus();
return false;
}
if (!reg_first_name.test(first_name)) {
alert('Please enter only letters no special character allowed.');
document.getElementById("sa_first_name").focus();
return false;
}
return false;
});
Can you guide me?
In case the user enters a name the first_name.length > 0 will always be true.
You can check it like
if($.trim(first_name) == '')
to also avoid only spaces
condition is wrong
if(first_name.length > 0){
if you want to check that first_name must have value then your condition must be
if(first_name.trim().length == 0){

Anyone of two textfield validation

I have a forgot password form. It has two fields 1) email and 2) mobile. So what I need is a validation for it. like both field should not be empty, both field should not be filled, any one only should be filled. email should be in email format and mobile should only contain numbers.
javascript Code:
function validate_fgtmgrpwd(){
var adminid=document.f_mgr_password.mgrid;
var adminmobile=document.f_mgr_password.mgrmobile;
var mgr_length=document.f_mgr_password.mgrmobile.value;
if ((document.f_mgr_password.mgrid=="Ex: ManagerID#Email.com")||
(document.f_mgr_password.mgrid==""))
{}
{document.getElementById("validationMessage").innerHTML=" <font color='#FF0000'>Error: </font> Please Enter Either Email Id Or Mobile No:!";
popup('validationPopup');
mgrid.focus();
return false;
}
}
You should do the validation server side, not client side. There are always ways to get around your javascript form validation.
So you should check/validate the POST values in your php script, and act accordingly.
With html5 you can define an input type="email" for your email field ( so it parse properly inserted email ) and an input type="tel" for your mobile phone field. So, set the clear field at onfocus event for the other field. this should works fine.
Try this:
function validate_fgtmgrpwd() {
var adminid = document.f_mgr_password.mgrid,
adminmobile = document.f_mgr_password.mgrmobile,
emailExp = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/gi,
phoneExp = /^[0-9\-\+]{9,15}$/gi;
if(!adminid.value.length && !adminmobile.value.length){
alert("At Least one field is mandatory!");
adminid.focus();
return false;
} else {
if(adminid.value.length && !emailExp.test(adminid.value)){
alert("Enter a valid email");
adminid.focus();
return false;
} else if(adminmobile.value.length && !phoneExp.test(adminmobile.value)) {
alert("Enter a valid phone number");
adminmobile.focus();
return false;
} else {
return true;
}
}
}
For HTML5 supporting browsers, native validation will work and for other browsers, custom validation will work.
jsfiddle: http://jsfiddle.net/MR6bD/2/

Categories