Native Form Validation
Bootstrap4 with Native Form Validation
by aalfiann
HTML
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/native-form-validation@1.1.0/dist/formvalidation.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Form Login</title>
</head>
<body>
<h1>Form Login</h1>
<form>
<div id="email_group" class="form-group">
<label for="email">Email address</label>
<input id="email" type="email" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
<small id="email-error" class="form-text text-danger"></small>
</div>
<div id="password_group" class="form-group">
<label for="password">Password</label>
<input id="password" type="password" class="form-control" placeholder="Password">
<small id="password-error" class="form-text text-danger"></small>
</div>
<div id="checkbox_group" class="form-check">
<input id="checkbox" type="checkbox" class="form-check-input">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
<small id="checkbox-error" class="form-text text-danger"></small>
</div>
<button id="submit_login" type="button" class="btn btn-primary">Login</button>
<button id="submit_reset" type="button" class="btn btn-secondary">Reset</button>
</form>
</body>
</html>
JavaScript
var FV = new FormValidation();
FV.rules({
password: {
required: true,
message: 'Password must be min 3-20 chars!',
minLength:3,
maxLength:20,
errorPlace:'password-error',
errorAddClass: {
password_group:'has-danger',
password:'is-invalid'
}
},
email: {
required:true,
regex: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/,
errorPlace:'email-error',
errorAddClass: {
email_group:'has-danger',
email:'is-invalid'
}
},
checkbox: {
message: 'You have to check this first!',
method: function(element) {
return element.checked;
},
errorPlace:'checkbox-error',
errorAddClass: {
checkbox_group:'has-danger',
checkbox:'is-invalid'
}
}
});
$(document).ready(function(){
$('#email').on('blur', function() {
FV.element(this.id).validate();
});
$('#password').on('blur', function() {
FV.element(this.id).validate();
});
$('#submit_login').on('click', function() {
if(FV.validate().isValid()) {
alert('validate success!');
}
});
$('#submit_reset').on('click', function() {
$('#email').val('');
$('#password').val('');
FV.reset();
});
});