How to validate already created form using jquery , bootstrap - asp.net-mvc

I have login form with two field User Name and password.These fields are validated .But Now I want to change it in Registration Form by adding more fields like password and confirm password and email now how can i make sure that password entered is matched with confirm password field and similarly how to validate email field.
Login form
<!-- Modal content-->
<div class="modal-content">
<section id="content1">
<form>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1 class="modal-title">Signin Form</h1>
</div>
<div class="modal-body">
<input type="text" placeholder="Username" required="" id="username" />
<input type="password" placeholder="Password" required="" id="password" />
</div>
<div class="modal-footer" style="padding-left:86px">
<input type="submit" value="Log in" style="background-color:whitesmoke" />
</div>
</form>
<!-- form -->
</section>
<!-- content -->
<!-- container -->
//</div>
and i added these three files.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

For email validation, we can use regex expression:
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};
This will true or false on valid email address
For password validation:
function ValidatePassword(){
var password = $("#password").val();
var confirmPassword = $("#confirm-password").val();
if (password != confirmPassword ) {
return false;
} else {
return true;
}
}

You have to create new fields for confirm password and email address.
<input type="password" required="" id="confirmPassword" />
<span id='message'></span>
<input type="email" required="" id="emailAddress" />
<input type="submit" value="Log in" id="submitButtonId" style="background-color:whitesmoke" />
If you are using HTML5, you can use the input type = "email" otherwise use this
pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
Then in Javascript you can validate the value of Password and confirm password field as:
var password = $("#password").val();
var confirmPassword = $("#confirmPassword").val();
if (password != confirmPassword ) {
$('#message').html('Matching');
$('#submitButtonId').prop('disabled', false);
} else {
$('#message').html('Not Matching');
$('#submitButtonId').prop('disabled', true);
}
If, you want to do it before submitting, you can use the following code:
$('#password, #confirmPassword').on('keyup', function () {
if ($('#password').val() == $('#confirmPassword').val()) {
$('#message').html('Matching').css('color', 'green');
$('#submitButtonId').prop('disabled', false);
} else{
$('#message').html('Not Matching').css('color', 'red');
$('#submitButtonId').prop('disabled', true);
}
});

Since JQuery is already a requirement of Bootstrap you could use the following validation plugin to validate the password fields: https://github.com/1000hz/bootstrap-validator/
You could use a code like this to validate the passwords
<!-- New password row -->
<div class="form-inline row">
<!-- 50% -->
<div class="form-group col-sm-6">
<!-- First password input field with custom minlength attribute -->
<input type="password" data-minlength="6" class="form-control" id="password" placeholder="Password"
required>
<!-- Block with requirement -->
<div class="help-block">Minimum of 6 characters</div>
</div>
<!-- 50% -->
<div class="form-group col-sm-6">
<!-- Input field with custom error message when passwords don't match -->
<input type="password" class="form-control" id="passwordConfirm" data-match="#password"
data-match-error="Whoops, these don't match" placeholder="Confirm" required>
<!-- Block to show error message -->
<div class="help-block with-errors"></div>
</div>
</div>
You will need to add an ID attribute to the form and activate the validator plugin.
$('#myForm').validator();
Keep in mind that you never need to rely on JavaScript only and it's always a must to validate the password server-side.

Related

How to compare emails in javascript?

I am trying to make an edit profile page in which user can update its current email or pwd by inputting current email and password and then give new ones. I am also sending whole data of user(including username and password) when he sign in through viewdata.
#{
var user = (User)ViewData["User"];
}
<div class="account-info mt-3">
<fieldset class="border border-dark p-3">
<legend class="float-none w-auto">Account Info</legend>
<div class="mb-3 simpleinfo">
<label for="email" class="form-label">Enter Your Current Email</label>
<input type="email" class="form-control" name="Username" id="prevemail"/>
</div>
<div class="mb-3 simpleinfo">
<label for="prevpwd" class="form-label">Enter Your Current Password</label>
<input type="password" class="form-control" name="Pwd" id="prevpwd"/>
<button type="button" class="btn btn-success mt-4 checkcred">Update Credentials</button>
</div>
<div class="mb-3 simpleinfo">
<label for="email" class="form-label">Enter new Email</label>
<input asp-for="Username" disabled type="email" class="form-control" id="newemail">
</div>
<div class="mb-3 simpleinfo">
<label for="newpwd" class="form-label">Enter New Password</label>
<input type="password" disabled class="form-control" asp-for="Password" id="newpwd">
</div>
</fieldset>
</div>
Now i want to compare the email that user enters and the email that is present in the user object.
here's my code for this:
<script>
$('.checkcred').click(function() {
var prevemail = $('#prevemail').val();
var prevpassword=$('#prevpwd').val();
if(prevemail==#user.Username&&prevpassword==#user.Password)
{
alert("Validated");
}
else
{
alert("not validated");
}
});
</script>
But it is giving me syntax error on Console: Invalid or unexpected token.
Please lemme know what i am doing wrong.

How to make 'email' input filed error message to display outside the input box?

I'm using reactive-form and have multiple input fields with respective mat-error for each. All of the input fields error messages appear outside of the input box, which is correct and is by default. But the email input field is the only one, that it's error message appears inside the input field.
Here's the code
<!-- username -->
<div class="">
<mat-form-field class="">
<input type="email" matInput
placeholder="Email"
formControlName="username" required>
<div *ngIf="isFieldValid('username')">
<mat-error
*ngIf="modelForm.controls['username'].hasError('required')
&&
modelForm.get('username').touched">
This is required
</mat-error>
<mat-error
*ngIf="modelForm.controls['username'].hasError('pattern')">
Email invalid
</mat-error>
<mat-error
*ngIf="!modelForm.controls['username'].hasError('required')
&&
!modelForm.controls['username'].hasError('pattern')
&&
modelForm.controls['username'].hasError('isDupe')">
This email has been used already
</mat-error>
</div>
</mat-form-field>
</div>
<!-- password -->
<div class="">
<mat-form-field class="">
<input matInput type="password" placeholder="Password"
formControlName="password" required>
<mat-error
*ngIf="password.hasError('required')">
This is required
</mat-error>
<mat-error
*ngIf="password.hasError('pattern')">
Password should contain at least one number
</mat-error>
</mat-form-field>
</div>
I want to make email error message appear below input field similar to the password error message.
Remove <div *ngIf="isFieldValid('username')">
Inside Html file go this way:
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<form/>
And In TS File:
export class AppComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required]
});
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value))
}
}
And this Line <div *ngIf="isFieldValid('username')">
doesn't allow to create div totally

How to show password entered when checkbox is clicked?

in my form i have one checkbox so when i check the checkbox it should show password entered in password field.i am doing it using angular 7.
<div class="form-group">
<label for="Password" class="control-label">Password</label>
<div>
<input type="password" class="form-control" name="Password" ngModel
#pwd="ngModel" placeholder="Password" required pattern="^(?=.*[a-z])(?
=.*
[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$">
<div *ngIf= pwd.invalid>
<small class="form-text text-danger" *ngIf=
pwd.errors.required>Password Required</small>
<small class="form-text text-danger"
*ngIf=pwd.errors.pattern>Minimum eight characters, at least one
uppercase letter, one lowercase letter, one number and one special
character.</small>
</div>
</div>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input"
[disabled]="pwd.invalid">
<label class="form-check-label" id="show" for="exampleCheck1">Show
Password</label>
</div>
By checking the checkbox it should show password entered in the password field.
Hi and welcome on Stackoverflow!
Try to switch between type="password" and type="text" based on checkbox value.
Add #showPassword to your checkbox input, like that :
<input #showPassword type="checkbox" class="form-check-input" [disabled]="pwd.invalid">
Then on your password field :
<input type="showPassword.checked ? 'text' : 'password'" .... />
EDIT (in case you did not solve it yet, and for others) :
component.ts
// show/hide boolean variable
showPassword: boolean;
constructor() {
// init value in constructor
this.showPassword = false;
}
// click event, show/hide based on checkbox value
showHidePassword(e) {
this.showPassword = e.target.checked;
}
component.html
<input [type]="showPassword ? 'text' : 'password'" />
<input type="checkbox" (change)="showHidePassword($event)" > toggle view

Best way to prevent HTML Code in Textbox MVC Razor View

I have following code on my view.
This HTML code is used for search in website.
This view is not strongly typed view, so I can apply use DataAnnotation through model.
What is best view to validate that, this textbox should accept only alpha numeric characters?
HTML
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" placeholder="search" class="fullwidth" onkeypress="return BlockingHtml(this,event);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
Javascript
function BlockingHtml(txt) {
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}
Model:-
[StringLength(100)]
[Display(Description = "Name")]
[RegularExpression("(/[^a-zA-Z 0-9\n\r.]+/g", ErrorMessage = "Enter only alphabets and numbers of Name")]
public string Name{ get; set; }
Updated:-
View:-
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" id="txt" placeholder="search" class="fullwidth" onkeypress="BlockingHtml(this);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
function BlockingHtml(txt) {
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" placeholder="search" class="fullwidth" onblur="return BlockingHtml(this,event);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
Changed event onkeypress to onblur.

How can I show a validation div when data-validation triggers

Instead of styling the data-valmsg-summary produced by Html.ValidationSummary() in a custom way, I would like to just show the box with the twitter bootstrap style applied to it whenever the field validation fails. How would I go about doing this? Currently my markup looks like this:
..
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<div class="container">
<div class="row-fluid">
<br />
<br />
<br />
<br />
</div>
<div class="row-fluid">
<form class="navbar-form pull-right" action="/Login?ReturnUrl=%2F" method="post">
<h3 class="modal-header">Please sign in</h3>
<input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" class="input-large" placeholder="Username">
<input data-val="true" data-val-required="The Password field is required." id="Password" name="Password" type="password" class="input-large" placeholder="Password">
<label class="checkbox">
<input type="checkbox" value="remember-me">
Remember me
</label>
<button type="submit" class="btn btn-danger">Sign in</button>
<br />
<br/>
<div data-valmsg-summary="true" class="alert alert-danger alert-block" id="formval" >
<span class="close pull-right" data-dismiss="alert">×</span>
<strong>Ooops!</strong> You seem to be missing something:
<ul>
<li style="display: none"></li>
</ul>
</div>
</form>
</div>
</div>
I've tried adding the style="display: none" to my div, but that does not seem to do the trick either.
I was looking for something else and stumbled on this. Thought I would post the answer for the next person since I am 5 months late. Add to your document ready.
//I dont want to validate my ajax forms take that if statement out if you want 2.
if ($('form:not([data-ajax="true"])').length != 0) {
var settings = $.data($('form:not([data-ajax="true"])')[0], 'validator').settings;
settings.submitHandler = function (form) {
//success
form.submit();
};
}
$("form").bind("invalid-form.validate", function (form, validator) {
var errors = validator.numberOfInvalids();
var message = "<ul>";
//loop thru the errors
for (var x = 0; x < validator.errorList.length; x++) {
var $group = $(validator.errorList[x].element).parent().parent(); //gets bootstrap class of form-group
var $element = $(validator.errorList[x].element); // gets the element to validate
var elementMessage = validator.errorList[x].message; // gets the message
$group.addClass("has-error"); // adds the bootstrap class has-error to the group
$element.popover({ content: elementMessage, placement: "right" }).popover("show"); // adds a popover
message += "<li>" + elementMessage + "</li>"; //appends message to list
}
message += "</ul>";
// Function I have to add alert to the page, but basically you can do whatever you want with the message now.
RegisterError("There was some errors with your submission!", message, false);
});

Resources