How can I check minlength and restrict special characters with Vue Js? - javascript

Good afternoon or at least in my country ^_^
I'm basically trying to do a full validation before submitting a form using the Vue Js library, on this snippet I'm checking if a input is empty.
const app = new Vue({
el: '#app',
data: {
name: null
},
methods:{
checkForm: function (e) {
if (this.name) {
return true;
}
if (!this.name) {
console.log("Please write your name :)")
}
e.preventDefault();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" #submit="checkForm" method="post">
<input type="text" v-model="name">
<input type="submit">
</form>
As you can see it works. But I want to increase security by adding a restriction for special characters and also detect a minlenght.
I try to search the internet for functions that allow me to do what I am looking for. But I can't find anything.

#catawP, i edited your snippet to allow checking for length and for special characters.
const app = new Vue({
el: '#app',
data: {
name: null,
email: null
},
methods:{
checkForm: function (e) {
e.preventDefault();
// if you want to check both fields
if(this.checkField(this.name, 'name') && this.checkField(this.email, 'email')) return true
// if you want to check only one field
if(this.checkField(this.email, 'email')) return true
},
checkField(value, field){
if (value) {
if(value.length < 10 && field === 'name'){ // check the length only for name field
console.log("The " + field + " should contain at least 10 characters!")
}else if(/[;,.]/.test(value) && field !== 'email'){ // exclude email field from this check
console.log('No special characters are allowed')
}else if(field === 'email' && !this.email.includes('#')){ // ex of custom checks for a specific field
console.log('Email field should contain #')
}else{
return true;
}
}
if (!value) {
console.log("Please write your " + field + " :)")
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" #submit="checkForm" method="post">
<label for="name">Name</label>
<input type="text" v-model="name" id="name">
<label for="email">Email</label>
<input type="text" v-model="email" id="email">
<input type="submit">
</form>

Checking the length can be done with the .length property. So you could add:
if(this.name.length < 30) {
console.log('Name must have 30 characters or more.');
}
Of course you don't want to use console.log for your form validation, but you did above in your first check so I repeated it. Also, 30 was arbitrary, you would change that to what you want.
As for "special characters", what do you mean? Do you want to disallow certain characters or only allow some characters? If you want to disallow some characters, you could use a regular expression and use test to see if it exists. For example:
let badchrs = /[$%\^]/;
if(badchrs.test(this.name)) {
console.log("you can't use $ or % or ^");
}
To only allow letters, you could do like so:
s = 'raymond';
badchrs = /^[a-z]/;
console.log(badchrs.test(s));

Related

How to perform string methods on function parameter in javascript

I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}

I want to add an alert in the if else statement. How do I do that?

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

Validate email id on keypress in jquery [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 9 months ago.
Referring to this issue:
How can I set a minimum length for a field with jQuery?,
<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>
What would the code be for settting a minimum length for a field with jQuery?
$('#new_invitation').submit(function(event) {
if ($('#invitation_form_recipients input').filter(function() {
return $(this).val();
}).length == 0) {
// All the fields are empty
// Show error message here
// This blocks the form from submitting
event.preventDefault();
}
});
How can I validate that every field input have a valid email address with jQuery? In the above code?
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}​
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
Email: {
group: '.col-sm-3',
enabled: false,
validators: {
//emailAddress: {
// message: 'Email not Valid'
//},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'Email not Valid'
},
}
},
This : /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i is not working for below Gmail case
gmail.#gmail.com
gmail#.gmail.com
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
Regex Solution link
/(?:((?:[\w-]+(?:\.[\w-]+)*)#(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
This :
var email = /^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
function mailValidation(val) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(val)) {
$('#errEmail').text('Please enter valid email.');
}
else {
$('#errEmail').hide();
}
}

Input type validations are not working for the very first time after page loads

I have a text box, in that I wants to allow only alphabets.
Below is my code :
state ={
NomName: '',
}
onlyAlpha(e) {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
render = () => {
return (
<label for="nominee">Nominee name</label>
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha.bind(this)} autoComplete="off"
maxLength="100"/>
)}
The input validations are not working (I am able to enter Numbers) at very first time after page loads. But once you cleared the field and try to re-enter the value it won't takes numbers (It works).
How can I make it run at each and every time.?
Please let me know if I am doing anything wrong.
I suggest you start using fat arrow functions. Make the onlyAlpha function like so:
onlyAlpha = (e) => {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
This would remove the usage of this.onlyAlpha.bind(this).
Also, I think you should pass the function to the onChange listener like so:
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha} autoComplete="off"
maxLength="100"/>

jQuery Validate: Validate that one field, or both fields of a pair are required

I have a form that I am trying to validate that has two fields:
<div class="entryForm">
<div class="formField">
<label for="fieldEmailAddress">Email address:</label>
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
</div>
<div class="formField">
<label for="fieldMobileNumber">Mobile number:</label>
<input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
</div>
</div>
Here's my jQuery Validation wireup:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
});
</script>
What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.
Any ideas?
You can bypass the Validate plugin and do a check like the following:
$("#form1").submit(function() {
var email = $('#fieldEmailAddress');
var phone = $('#fieldMobileNumber');
if(email.val() == '' && phone.val() == '') {
alert('Fill out both fields');
}
else if(email.val() == '') {
alert('Email, please...');
}
else if(phone.val() == '') {
alert('Phone, please...');
}
else {
alert('Yay!');
}
});
You simply need to include the additional-methods.js file and use the require_from_group method.
require_from_group: [x, '.class']
// x = number of items required from a group of items.
// .class = class assigned to every form element included in the group.
jQuery:
$(document).ready(function () {
$('#form1').validate({
rules: {
fieldMobileNumber: {
phoneUS: true,
require_from_group: [1, '.mygroup']
},
fieldEmailAddress: {
require_from_group: [1, '.mygroup']
}
},
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
});
});
Add class="mygroup" to each input you need to group together...
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress" class="mygroup" />
And finally, optionally use the groups option to lump the messages into one...
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
Working DEMO: http://jsfiddle.net/CYZZy/
If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement callback function.

Categories

Resources