I want my page to splurt a message if my pattern matches my regex and I don't know why this is not doing anything.
html:
<div class="third">
<label> Enter Password: </label>
<input type="text" name="pword1" class="iBox" id="pword1" onmouseout="HideToolTip()" onmouseover="ShowToolTip()" onkeyup="allFunctions()" placeholder="choose a password" autocomplete="off">
<p id="tooltipbox">Password must be between 8-16 characters, contain an uppercase, lowercase, number and special character</p>
</div>
js:
function reqMetVal(){
var pwfs = document.getElementById("pword1").value;
var re = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\.,\[\]_£|\`¬':\;\~{}<>()#?!\#$\%^&*-]).{8,20}$";
if(pwfs.match(re)){
DIMR = "Requirements MET";
}else if (pwfs.length < 1){
DIMR = "";
}
else{
DIMR = "Requirements NOT MET";
}
document.getElementById("reqMeeting").innerHTML = DIMR;
}
Related
I want to verify and validate a form in HTML, and insert messages in Front if necessary ("eg.Pseudo/Username not long enough"), which will serve as a "new user" form for a website.
I want to start by understanding my mistake for the "Pseudo" verification and validation.
I currently have the following in HTML:
<form id="formNouveau" onsubmit="return valideForm2()">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS (focusing on the pseudo validation):
function valideForm(){
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
function valPseudo(text)
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of text.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert ("Please write a pseudo");
if (letterCount + numberCount > 40)
alert ("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert ("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert ("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert ("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
}
What do you think?
Thank you!
You have a mix of variable names in the function and a sub function with incorrect syntax. You're not preventing the form from submitting. Fixed both and it works:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert("Please write a pseudo");
if (letterCount + numberCount > 40)
alert("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
<form id="formNouveau">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
function valideForm2(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
console.log(valPseudo);
function validate(text) {
let letters = "abcdefghijklmnopqrstuvwxyz";
let numbers = "0123456789";
let letterCount = 0;
let numberCount = 0;
for (let character of text.toLowerCase()) {
if (letters.includes(character)) ++letterCount;
else if (numbers.includes(character)) ++numberCount;
else return false; //A non [a-zA-Z0-9] character was present
}
if (text == "") alert("Please write a pseudo");
if (letterCount + numberCount > 40) alert("Pseudo is too long"); //The name is too long
if (letterCount + numberCount < 5) alert("Pseudo is too short"); //The name is too short
if (letterCount < 1) alert("one letter needed at least"); //There aren't enough [a-zA-Z] characters
if (numberCount < 1) alert("one number needed at least"); //There aren't enough [0-9] characters
return 0; //Everything is okay!
}
validate(valPseudo);
}
const form = document.getElementById("formNouveau");
form.addEventListener("submit", valideForm2);
Try this JS code instead, it has the same functionality but has some modifications, the main problem was regarded to e.preventDefault() which forces page not to reload. Moreover you had some little bugs. For more information on preventDefault you can visit link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You're better off testing the input against a REGEX expression rather than testing for each failure case...
There a numerous REGEX testers and cheat-sheets online for what you're trying to do.
I want to validate my form now, and I wrote some code, it's working perfectly for length constraints but I want to use Regular Expression to filter the values of each element.
I found from a forum, these Regular Expressions:
for Full Name: var regex = /^[a-zA-Z ]$/;
for Phone: var regexPhone= /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
I guess the HTML5 (input:type email) is enough for email validation
Also I want to do this with the name, that when I type the full name, the first letters change to uppercase letters. For example--> input="john smith", changes to "John Smith".
This is my code:
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if(pedio.id.indexOf("Name")!=-1){
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if(pedio.id.indexOf("Phone")!=-1){
if (pedio.value.length!=10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail"autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br>
-If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>
Option 1: You can use text-transform: capitalize CSS property which will automatically do the task of converting a name from john cena to John Cena.
Check the example below in the CSS
Option 2:
I have added a new input called Nick name which uses javascript to do the same task.
I have used keyup handler to capture the all key input event so that we can execute a piece of code which will do the job on capitalizing the name.
The result is simple string manipulation which splits the name with <space-character> and converts the first character to uppercase and joins the same with rest of the string.
document.addEventListener("DOMContentLoaded", function() {
document.querySelector("#NickName").addEventListener("keyup", capitalizeName);
});
function capitalizeName() {
if (!this.value) return;
var aNewName = this.value.split(" ").map(function(name) {
return name.charAt(0).toUpperCase() + name.substring(1);
});
this.value = aNewName.join(" ");
}
function validateForm() {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var pedio = document.forms[0].elements[i];
if (pedio.id.indexOf("Name") != -1) {
if (pedio.value.length < 5 || pedio.value.length > 35) {
alert("Full Name must be 5-35 character long");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
if ((pedio.id.indexOf("Phone") != -1) && (isNaN(pedio.value))) {
alert("Phone is must contain only numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
if (pedio.id.indexOf("Phone") != -1) {
if (pedio.value.length != 10) {
alert("Phone must be 10 numbers");
pedio.focus();
pedio.style.backgroundColor = "#997379";
return false;
}
}
}
}
/* No CSS */
#Name {
text-transform: capitalize;
}
<h1 class="Title">Sign Up</h1>
<div>
<form method="post" onsubmit="return validateForm()">
<input type="text" id="Name" name="yourname" placeholder="*Full Name" autocomplete="off" required>
<input type="text" id="NickName" name="NickName" placeholder="*Nick name" autocomplete="off" required>
<input type="email" id="Email" name="youremail" placeholder="*E-Mail" autocomplete="off" required>
<input type="tel" id="Phone" name="yourphone" placeholder="*Phone" autocomplete="off" required>
<input type="password" id="Password" name="yourpassword" placeholder="*Password" autocomplete="off" required>
<p class="signup"> The fields with * are required!<br> -If you have an account, <a class="signup" href="reservation.php">log in</a> now-</p>
<keygen name="security" style="display:none;">
<input type="submit" value="Register">
</form>
</div>
Hint:
The RegExp object has a method test which when given a string argument returns true if there was at least one match in the str or false. MDN Documentation
Used as /regexp/.test(str). You already have code that tests for length. You want to test for the length AND for this regex.
When you want to capitalize the first letter of each word, that is called Title Case. There's an excellent answer here for that part of your question
please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>
I am validating the email by adding the user and email to the list, the pattern that I provided is not working for some patterns like xyz.xyz kkk.kk and my message is not displaying when it is validating Here is my code..
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
email.innerHtml = "Please enter valid emailid";
return false;
}
CSS
.errorclass{
border: 1px red solid;
}
Replace
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
with
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
Refer JavaScript Regular Expression Email Validation
So basically it's form validation. In the if statement for the reg ex to check the fullname.value, I can't figure out why it does not add the error message to the array. I've tested with a NOT in front but still doesn't seem to get into the else if statement block to add the error message or it skips it entirely. I have added the code below, also I've commented to section that does not function how I thought it would in my head. Look down to the script area.
<html>
<head>
<title>Form Validation</title>
<style type="text/css">
#error {color:red;}
</style>
</head>
<body>
<h1>Form Validation with Reg Expressions</h1>
<div id="error">
</div>
<form method="post" action="https://csu.mohawkcollege.ca/tooltime/echo.php" onSubmit="return validateForm(this)">
<div>
<label for="fullname">Full Name:</label>
<input id="fullname" type="text" name="fullname"/>
Salutation of Mr. or Mrs. followed by two text strings separated by any number of spaces.
</div>
<div>
<label for="street">Street:</label>
<input id="street" type="text" name="street"/>
2 or 3 digit number followed by a text string ending with Street or Road separated by any number of spaces.
</div>
<div>
<label for="postalcode">Postal Code:</label>
<input id="postalcode" type="text" name="postalcode"/>
Char Char Digit optional Hyphen or space Char Digit Digit (abclxyz and number 0 not allowed. Case insensitive.)
</div>
<div>
<label for="phone">Phone:</label>
<input id="phone" type="text" name="phone"/>
10 digits, first 3 digits have optional parentheses, either side of digits 456 are optional space, dot or hyphen.
</div>
<div>
<label for="email">Email:</label>
<input id="email" type="text" name="email"/>
firstname.lastname#mohawkcollege.domain (firstname and lastname must be 4-10 characters in length, domain may be either .com, .ca, or .org)
</div>
<input type="submit"/>
</form>
<script type="text/javascript">
var displayErrorMessage = document.getElementById("error");
function validateForm(form)
{
displayErrorMessage.innerHTML = "";
var errorMessages = [];
alert("validate function entered");
// ERROR HAPPENS HERE!!
// DOES NOT SEEM TO GET INTO THE ELSE IF BLOCK TO ADD ERROR MESSAGE TO THE ARRAY
if (form.fullname.value == "") errorMessages.push("Full Name cannot be empty");
else if (!/^(Mr\.|Mrs\.) *[a-zA-Z]+ *[a-zA-Z]+$/.match(form.fullname.value))
{
errorMessages.push("Name format error. Ex. Mr. John Smith");
}
if (form.street.value == "") errorMessages.push("Street cannot be empty");
if (form.postalcode.value == "") errorMessages.push("Postal Code cannot be empty");
if (form.phone.value == "") errorMessages.push("Phone cannot be empty");
if (form.email.value == "") errorMessages.push("Email cannot be empty");
alert(errorMessages.length);
if (errorMessages.length == 5)
{
var unorderedList = document.createElement("ul");
var list = document.createElement("li");
list.innerHTML = "Please fill something in. All fields are blank!";
unorderedList.appendChild(list);
displayErrorMessage.appendChild(unorderedList);
return false;
}
else if (errorMessages.length > 0)
{
var unorderedList = document.createElement("ul");
for (var n in errorMessages)
{
var list = document.createElement("li");
list.innerHTML = errorMessages[n];
unorderedList.appendChild(list);
}
displayErrorMessage.appendChild(unorderedList);
return false;
}
else
{
alert("Got your info -- now the form will be submitted!");
return true;
}
}
</script>
</body>
Try using
!form.fullname.value.match(/^(Mr\.|Mrs\.) *[a-zA-Z]+ *[a-zA-Z]+$/)
The method is string.match(regexp) not the other way around.
e.g.
'Mr. OG Haza'.match(/^(Mr\.|Mrs\.) *[a-zA-Z]+ *[a-zA-Z]+$/)
Output: ["Mr. OG Haza", "Mr."]