-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.js
68 lines (62 loc) · 1.85 KB
/
validator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import crypto from 'crypto';
export class Validator {
/**
* Checks if a string is a valid email address.
* @param {string} email - The email address to validate.
* @returns {boolean} Returns true if the email is valid, false otherwise.
*/
static isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
/**
* Checks if a string is a valid URL.
* @param {string} url - The URL to validate.
* @returns {boolean} Returns true if the URL is valid, false otherwise.
*/
static isValidURL(url) {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
}
/**
* Checks if a value is a number.
* @param {*} value - The value to check.
* @returns {boolean} Returns true if the value is a number, false otherwise.
*/
static isNumber(value) {
return typeof value === 'number' && isFinite(value);
}
/**
* Checks if a string is a valid phone number.
* @param {string} phoneNumber - The phone number to validate.
* @returns {boolean} Returns true if the phone number is valid, false otherwise.
*/
static isValidPhoneNumber(phoneNumber) {
const phoneRegex = /^\d{10}$/;
return phoneRegex.test(phoneNumber);
}
/**
* Hashes a password using SHA-256.
* @param {string} password - The password to hash.
* @returns {string} The hashed password.
*/
static hashPassword(password) {
const hash = crypto.createHash('sha256');
hash.update(password);
return hash.digest('hex');
}
/**
* Checks if a password matches a given hash.
* @param {string} password - The password to check.
* @param {string} hash - The hash to compare against.
* @returns {boolean} Returns true if the password matches the hash, false otherwise.
*/
static checkPassword(password, hash) {
const hashedPassword = Validator.hashPassword(password);
return hashedPassword === hash;
}
}