NIC and username validation field - javascript

I have two fields, the NIC and the username. Their validation are
NIC check for numbers or characters
username field must contain more than 8 characters including the date
of birth from the NIC.
So far I tried this for my NIC.
function validateNIC()
{
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
message1.innerHTML="Length must be 14 characters";
} else{
message1.innerHTML="Length is good";
}
}
<div class="form-group">
<label for="username"><span class="req">* </span> NIC NUMBER:</label>
<input class="form-control" type="text" name="NIC" id = "NIC" required onkeyup = "validateNIC();" maxlength=14 />
<span id="message1"></span>
</div>
And for my username I tried this.
function Validate(txt) {
txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
}
<div class="form-group">
<label for="username"><span class="req">* </span> User name:</label>
<input class="form-control" type="text" name="username" id="txt" onkeyup="Validate(this)" maxlength=14 required />
<div id="errLast"></div>
</div>
My validation for the NIC is not quite working.It keeps showing
"Length must be 14 characters" even if the length is good.
And for the username part, can anyone tell me how to do it ? Is
there an array I must do or something ? An example of the NIC is
T2108974302906 where 210897 is the DOB.

var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
Here NIC refers to the DOM element, not the value of that input element.
You want to use nic.value.length.
As for the username, your RegEx looks strange [^a-zA-Z-'\n\r.]. This set matches characters that are not in the set. Why did you put \n and \r?
Anyway, if you are using a <form> element to submit these field, I suggest you use pattern attribute. You can test yoru patterns on http://regex101.com/
To extract the DOB:
<input pattern="^T[0-3]\d[0-1]\d{10}$">
validateNIC() {
var nic = document.getElementById('NIC');
var isValid = /^T[0-3]\d[0-1]\d{10}$/.test(nic.value);
var dob = nic.value.substring(1, 7);
}

var nic = document.getElementById('NIC');
This statements gets the input element - not its value. You need to get its value as such:
var nic = document.getElementById('NIC').value;
Then, you can compare the length to 14. I would also suggest using !== instead of !=.
Username validation - why are you replacing the value if you're trying to validate? And why is your max value 14 and not 8?

Related

How to validate if the input text (in html) is a valid Phone Number when user hits the 11th number?

I have an input.
<input id="phoneNumber"/>
How can I validate if the inserted value from user is a valid phone number or not using jQuery ?
Thanks.
You can use oninput to check if input has some values entered or not.
When 10th value is entered you can use a alert but this will not be enough because after alert, user can still enter more values. So use maxlength="10" to allow only 10 numbers.
Also if you don't want to allow text but numbers only than you can use .replace(/[^\d]/, '') to replace any non-number . And show that it is not a number.
function validPhone(phoneNum)
// check for valid phone numbers in the format 999-999-9999
{
if (phoneNum.value.match(/[^\d]/)) {
phoneNum.value = phoneNum.value.replace(/[^\d]/, '')
document.querySelector("#demo1").innerHTML = "Sorry numbers only";
} else {
document.querySelector("#demo1").innerHTML = "";
}
var strPhone = phoneNum.value;
var rePhone = /\d{3}-\d{3}-\d{4}/;
if (strPhone.length >= 10) {
phoneNum.select();
document.querySelector("#demo1").innerHTML ="No more numbers plz, only 10 digits allowed in Phone number.";
}
document.querySelector("#demo").innerHTML = strPhone.length;
};
#demo1 {
color: red;
}
<input class="form-control" oninput="validPhone(this)" type="text" name="username" placeholder="Enter Phone number" maxlength="10" id="phoneNumberForForgotPassword" data-val-required="نام کاربری را وارد نمائید.">
<div id="demo1"></div>
<div id="demo"></div>

Multiple Form Validation in JS using Class

I want to validate 2 html forms - First form is on the FAQ page and the second form is on the contact us page. Both forms have name and phone as common input fields so I want to validate both form conveniently in JS by using Class.
My JS code is as follows for validating Name and Phone input field for FAQ form.
class FormValidate {
constructor(nameField, phoneField, emailField, form) {
this.nameField = nameField; // name input field
this.phoneField = phoneField; // phone input field
this.emailField = emailField; // email input field
this.form = form;
}
// method for validation of name input
validateName(nameField) {
const regName = new RegExp("^[a-zA-Z\\s]*$");
let isNameValid = false;
let name_z = nameField.value.trim(); // input value of Name input field
let isNameHasValidLength = name_z.length < 3 || name_z.length > 20 ? false : true;
// Name input field is not empty and contain proper data -> Not Empty && value must be between 3 to 20 characters && follow reg expression for validation
if( !(name_z === '') && isNameHasValidLength && (regName.test(name_Z)) ){
isNameValid = true;
}
return isNameValid;
}
validatePhone(phoneField) {
let isPhoneValid = false;
let phone_z = phoneField.value.trim(); // input value of Phone input field
let isPhoneHasValidLength = phone_z.length < 10 || phone_z.length > 13 ? false : true; // making sure that phone number is between 10 to 13 digits -> +91 and rest 10 digits
const regPhone = new RegExp("^([0|+[0-9]{1,5})?([7-9][0-9]{9})$");
// Validating Phone Number -> Not Empty && Must have 10 to 13 digits only && follow reg expression for validation
if( !(phone_z === '') && isPhoneHasValidLength && regPhone.test(phone)) {
isPhoneValid = true;
}
return isPhoneValid;
}
}
let faqForm = new FormValidate(document.querySelector('#name'), document.querySelector('#phone'), null, document.querySelector('#faq-form'));
faqForm.form.addEventListener('submit', function(e) {
let nameOkay;
let phoneOkay;
let submitOkay;
nameOkay = faqForm.validateName(faqForm.nameField);
phoneOkay = faqForm.validatePhone(faqForm.phoneField);
submitOkay = nameOkay && phoneOkay;
// Prevent form submission if form input is not okay
if (!submitOkay) {
e.preventDefault();
}
});
HTML form code -
<form id="faq-form" action="mail-faq.php" method="POST">
<div class="faq-form-group"> <span class="faq-form-span-text">Name</span>
<input type="text" placeholder="i.e, John Smith" name="name" id="name" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Phone</span>
<input type="text" placeholder="+91 123456789" name="phone" id="phone" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Message</span>
<textarea placeholder="Your question" name="message" id="message" autocomplete="off" required></textarea>
</div>
<div class="faq-form-group">
<button class="faq-form-submit-btn" id="submit" type="submit" name="submit">Submit </button>
</div>
</form>
The problem is that nameField.value.trim(); and phoneField.value.trim(); statements are returning value - "" Which makes the validation false.
How can I fix this problem?
When you correct the typo here in (regName.test(name_Z)) (lowercase z) then the trimed vars are as expected (not "")...

JS Student Email Validation

I am a beginner in Javascript and am looking to find a solution to why the code below is not working.
I've reviewed several tutorials here on StackOverflow and believe it should work... but it's not.
The HTML looks like this:
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
<br>
</form>
<input type="button" onclick = "validateEmail()">
The Javascript looks like this:
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms[personalInfo].elements[Email].value;
if (reg.test(address) == false) {
alert ("Email not valid");
return false;
}
return true;
}
By my accounts, this should pop up an alert if the email address entered by the user is not valid.
Instead, nothing happens at all. I'm not sure if the test is even run.
function validateEmail() {
// There are, I feel, better version of this regex online
// You can check "https://emailregex.com/"
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
// document.getElementById() - Easier to read & understand, and more widely used
var address = document.getElementById('Email').value;
// Corrected your returns - not the main issue in the function, but the old
// returns might have caused confusion
if (reg.test(address) == false) {
alert("Email not valid");
return false
}
return true
}
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
</form>
<!-- You had a typo on the onclick but has since been fixed -->
<input type="button" onclick="validateEmail()" value="Submit">
Two issues here:
1- In your HTML, you are missing an = sign here: onclick"validateEmail()" (Edit: seems you fixed it now)
2- in your Javascript, the indices personalInfo and Email are strings, wrap them in quotation marks:
var address = document.forms['personalInfo'].elements['Email'].value;
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms['personalInfo'].elements['Email'].value;
if (reg.test(address)== false)
{
alert ("Email not valid");
return false
}
return true;
}
<form id="personalInfo">
<h2>Email: </h2> <input type="text" name="Email" id="Email"> <br>
</form>
<input type="button" onclick="validateEmail()">
When dealing with email inputs, set the input type to email instead of text - like so:
<input name="my-email" type="email" />"
Then the browser will perform validation on the input; such as if the input doesn't have the # present.

Regular expression to check only alphabets

I am trying to achieve form validation of only alphabets but this regular expression doesnt seem to work
function check() {
var reg="/^[a-zA-Z]*$/";
var x = document.forms['frm'].name.value;
var y= document.forms['frm'].email.value;
if( x === ""){
alert('Name field cant be empty');
$("#nameone").focus();
return false;
}
else if (!reg.match(x)){
alert('NAME must contain alphabets only');
return false;
}
else if( y === ""){
alert('Email field cant be empty');
$("#emailone").focus();
return false;
}
else {
return true;
}
}
this is my form ,i have added the details ,the input fields
<form class="reg_form" name='frm' method="post" onsubmit='return check();' >
<div class="input-field col-md-4">
<input type="text" placeholder="1. Name" name="name" id='nameone'/>
</div>
<div class="input-field col-md-4">
<input type="text" placeholder="2. Email" name="email" id='emailone' />
</div>
<div class="input-field col-md-4 ">
<input type="text" placeholder="3. phone" name="phone" />
</div>
</form>
In this case, your code isn't working 'cause your regex was set as a string in the line:
var reg="/^[a-zA-Z]*$/";
The regex was suposed to be set without quotes:
var reg=/^[a-zA-Z]*$/;
I suggest that instead of the method 'match', you use:
else if (!reg.test(x)){
This is more performatic and return a boolean value.
Instead of...
var reg = "/^[a-zA-Z]*$/"; // produces a **string**
You should omit the surrounding quotes:
var reg = /^[a-zA-Z]*$/; // produces a **Regex object**
The second uses javascript inline Regex syntax, with the slashes functioning as delimiters.
Furthermore you can use the simple .test() function to check if a string conforms to a Regex or not.
Demo:
var reg = /^[a-zA-Z]*$/;
console.log(reg.test("ABcd"));
console.log(reg.test("123"));
you can use
string.match("^[a-zA-Z]+$$");
you will get true if the string contains only letters and false otherwise

How do I prevent invalid characters from being entered into a form?

For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/

Categories

Resources