Home Web Front-end JS Tutorial Detailed explanation of Javascript sample code to determine whether a Crontab expression is legal

Detailed explanation of Javascript sample code to determine whether a Crontab expression is legal

Mar 18, 2017 pm 02:42 PM

这篇文章主要介绍了详解Javascript判断Crontab表达式是否合法的相关资料,需要的朋友可以参考下

Javascript判断Crontab表达式是否合法

这段时间在做Quartz任务调度,使用的Crontab表达式实现的。Crontab由前端页面输入,作为参数穿入后台。
虽然Quartz具有校验Crontab表达式的方法,如下:

boolean cronExpressionFlag = CronExpression.isValidExpression(crontab);
Copy after login

但是我一直想在前端直接验证,即不需要通过异步的方式向后台获取验证结果,找了好久,发现没有现成的框架可以使用,于是自己根据网上搜索到的资料,写了这个js脚本。

这个脚本目前对日和星期的判断还有点小问题,不过不影响使用。

以后如果有时间,继续完善这个脚本,废话不多说了,上代码:

 function cronValidate() {
    var cron = $("#cron").val();
    var result = CronExpressionValidator.validateCronExpression(cron);
    if(result == true){
      alert("格式正确"); 
    }
    else{
      alert("格式错误");
    }
    return CronExpressionValidator.validateCronExpression(cron); 
  } 
  function CronExpressionValidator() { 
  } 

  CronExpressionValidator.validateCronExpression = function(value) { 
    var results = true; 
    if (value == null || value.length == 0) { 
      return false; 
    } 

    // split and test length 
    var expressionArray = value.split(" "); 
    var len = expressionArray.length; 

    if ((len != 6) && (len != 7)) { 
      return false; 
    } 

    // check only one question mark 
    var match = value.match(/\?/g); 
    if (match != null && match.length > 1) { 
      return false; 
    } 

    // check only one question mark 
    var dayOfTheMonthWildcard = ""; 

    // if appropriate length test parts 
    // [0] Seconds 0-59 , - * / 
    if (CronExpressionValidator.isNotWildCard(expressionArray[0], /[\*]/gi)) { 
      if (!CronExpressionValidator.segmentValidator("([0-9\\\\,-\\/])", expressionArray[0], [0, 59], "seconds")) { 
        return false; 
      } 
    } 

    // [1] Minutes 0-59 , - * / 
    if (CronExpressionValidator.isNotWildCard(expressionArray[1], /[\*]/gi)) { 
      if (!CronExpressionValidator.segmentValidator("([0-9\\\\,-\\/])", expressionArray[1], [0, 59], "minutes")) { 
        return false; 
      } 
    } 

    // [2] Hours 0-23 , - * / 
    if (CronExpressionValidator.isNotWildCard(expressionArray[2], /[\*]/gi)) { 
      if (!CronExpressionValidator.segmentValidator("([0-9\\\\,-\\/])", expressionArray[2], [0, 23], "hours")) { 
        return false; 
      } 
    } 

    // [3] Day of month 1-31 , - * ? / L W C 
    if (CronExpressionValidator.isNotWildCard(expressionArray[3], /[\*\?]/gi)) { 
      if (!CronExpressionValidator.segmentValidator("([0-9LWC\\\\,-\\/])", expressionArray[3], [1, 31], "days of the month")) { 
        return false; 
      } 
    } else { 
      dayOfTheMonthWildcard = expressionArray[3]; 
    } 

    // [4] Month 1-12 or JAN-DEC , - * / 
    if (CronExpressionValidator.isNotWildCard(expressionArray[4], /[\*]/gi)) { 
      expressionArray[4] = CronExpressionValidator.convertMonthsToInteger(expressionArray[4]); 
      if (!CronExpressionValidator.segmentValidator("([0-9\\\\,-\\/])", expressionArray[4], [1, 12], "months")) { 
        return false; 
      } 
    } 

    // [5] Day of week 1-7 or SUN-SAT , - * ? / L C # 
    if (CronExpressionValidator.isNotWildCard(expressionArray[5], /[\*\?]/gi)) { 
      expressionArray[5] = CronExpressionValidator.convertDaysToInteger(expressionArray[5]); 
      if (!CronExpressionValidator.segmentValidator("([0-9LC#\\\\,-\\/])", expressionArray[5], [1, 7], "days of the week")) { 
        return false; 
      } 
    } else { 
      if (dayOfTheMonthWildcard == String(expressionArray[5])) { 
        return false; 
      } 
    } 

    // [6] Year empty or 1970-2099 , - * / 
    if (len == 7) { 
      if (CronExpressionValidator.isNotWildCard(expressionArray[6], /[\*]/gi)) { 
        if (!CronExpressionValidator.segmentValidator("([0-9\\\\,-\\/])", expressionArray[6], [1970, 2099], "years")) { 
          return false; 
        } 
      } 
    } 
    return true; 
  } 

  // ---------------------------------- 
  // isNotWildcard 静态方法; 
  // ---------------------------------- 
  CronExpressionValidator.isNotWildCard = function(value, expression) { 
    var match = value.match(expression); 
    return (match == null || match.length == 0) ? true : false; 
  } 

  // ---------------------------------- 
  // convertDaysToInteger 静态方法; 
  // ---------------------------------- 
  CronExpressionValidator.convertDaysToInteger = function(value) { 
    var v = value; 
    v = v.replace(/SUN/gi, "1"); 
    v = v.replace(/MON/gi, "2"); 
    v = v.replace(/TUE/gi, "3"); 
    v = v.replace(/WED/gi, "4"); 
    v = v.replace(/THU/gi, "5"); 
    v = v.replace(/FRI/gi, "6"); 
    v = v.replace(/SAT/gi, "7"); 
    return v; 
  } 

  // ---------------------------------- 
  // convertMonthsToInteger 静态方法; 
  // ---------------------------------- 
  CronExpressionValidator.convertMonthsToInteger = function(value) { 
    var v = value; 
    v = v.replace(/JAN/gi, "1"); 
    v = v.replace(/FEB/gi, "2"); 
    v = v.replace(/MAR/gi, "3"); 
    v = v.replace(/APR/gi, "4"); 
    v = v.replace(/MAY/gi, "5"); 
    v = v.replace(/JUN/gi, "6"); 
    v = v.replace(/JUL/gi, "7"); 
    v = v.replace(/AUG/gi, "8"); 
    v = v.replace(/SEP/gi, "9"); 
    v = v.replace(/OCT/gi, "10"); 
    v = v.replace(/NOV/gi, "11"); 
    v = v.replace(/DEC/gi, "12"); 
    return v; 
  } 

  // ---------------------------------- 
  // segmentValidator 静态方法; 
  // ---------------------------------- 
  CronExpressionValidator.segmentValidator = function(expression, value, range, segmentName) { 
    var v = value; 
    var numbers = new Array(); 

    // first, check for any improper segments 
    var reg = new RegExp(expression, "gi"); 
    if (!reg.test(v)) {  
      return false; 
    } 

    // check duplicate types 
    // check only one L 
    var dupMatch = value.match(/L/gi); 
    if (dupMatch != null && dupMatch.length > 1) { 
      return false; 
    } 

    // look through the segments 
    // break up segments on ',' 
    // check for special cases L,W,C,/,#,- 
    var split = v.split(","); 
    var i = -1; 
    var l = split.length; 
    var match; 

    while (++i < l) { 
      // set vars 
      var checkSegment = split[i]; 
      var n; 
      var pattern = /(\w*)/; 
      match = pattern.exec(checkSegment); 

      // if just number 
      pattern = /(\w*)\-?\d+(\w*)/; 
      match = pattern.exec(checkSegment); 

      if (match 
          && match[0] == checkSegment 
          && checkSegment.indexOf("L") == -1 
          && checkSegment.indexOf("l") == -1 
          && checkSegment.indexOf("C") == -1 
          && checkSegment.indexOf("c") == -1 
          && checkSegment.indexOf("W") == -1 
          && checkSegment.indexOf("w") == -1 
          && checkSegment.indexOf("/") == -1 
          && (checkSegment.indexOf("-") == -1 || checkSegment 
              .indexOf("-") == 0) && checkSegment.indexOf("#") == -1) { 
        n = match[0]; 

        if (n && !(isNaN(n))) 
          numbers.push(n); 
        else if (match[0] == "0") 
          numbers.push(n); 
        continue; 
      } 
  // includes L, C, or w 
      pattern = /(\w*)L|C|W(\w*)/i; 
      match = pattern.exec(checkSegment); 

      if (match 
          && match[0] != "" 
          && (checkSegment.indexOf("L") > -1 
              || checkSegment.indexOf("l") > -1 
              || checkSegment.indexOf("C") > -1 
              || checkSegment.indexOf("c") > -1 
              || checkSegment.indexOf("W") > -1 || checkSegment 
              .indexOf("w") > -1)) { 

        // check just l or L 
        if (checkSegment == "L" || checkSegment == "l") 
          continue; 
        pattern = /(\w*)\d+(l|c|w)?(\w*)/i; 
        match = pattern.exec(checkSegment); 

        // if something before or after 
        if (!match || match[0] != checkSegment) {  
          continue; 
        } 

        // get the number 
        var numCheck = match[0]; 
        numCheck = numCheck.replace(/(l|c|w)/ig, ""); 

        n = Number(numCheck); 

        if (n && !(isNaN(n))) 
          numbers.push(n); 
        else if (match[0] == "0") 
          numbers.push(n); 
        continue; 
      } 

      var numberSplit; 

      // includes / 
      if (checkSegment.indexOf("/") > -1) { 
        // take first # 
        numberSplit = checkSegment.split("/"); 

        if (numberSplit.length != 2) {  
          continue; 
        } else { 
          n = numberSplit[0]; 

          if (n && !(isNaN(n))) 
            numbers.push(n); 
          else if (numberSplit[0] == "0") 
            numbers.push(n); 
          continue; 
        } 
      } 

      // includes # 
      if (checkSegment.indexOf("#") > -1) { 
        // take first # 
        numberSplit = checkSegment.split("#"); 

        if (numberSplit.length != 2) {  
          continue; 
        } else { 
          n = numberSplit[0]; 

          if (n && !(isNaN(n))) 
            numbers.push(n); 
          else if (numberSplit[0] == "0") 
            numbers.push(n); 
          continue; 
        } 
      } 

  // includes - 
      if (checkSegment.indexOf("-") > 0) { 
        // take both # 
        numberSplit = checkSegment.split("-"); 

        if (numberSplit.length != 2) {  
          continue; 
        } else if (Number(numberSplit[0]) > Number(numberSplit[1])) { 
          continue; 
        } else { 
          n = numberSplit[0]; 

          if (n && !(isNaN(n))) 
            numbers.push(n); 
          else if (numberSplit[0] == "0") 
            numbers.push(n); 
          n = numberSplit[1]; 

          if (n && !(isNaN(n))) 
            numbers.push(n); 
          else if (numberSplit[1] == "0") 
            numbers.push(n); 
          continue; 
        } 
      } 

    } 
    // lastly, check that all the found numbers are in range 
    i = -1; 
    l = numbers.length; 

    if (l == 0) 
      return false; 

    while (++i < l) { 
      // alert(numbers[i]); 
      if (numbers[i] < range[0] || numbers[i] > range[1]) { 
        return false; 
      } 
    } 
    return true; 
  }
Copy after login

The above is the detailed content of Detailed explanation of Javascript sample code to determine whether a Crontab expression is legal. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do you know some reasons why crontab scheduled tasks are not executed? Do you know some reasons why crontab scheduled tasks are not executed? Mar 09, 2024 am 09:49 AM

Summary of some reasons why crontab scheduled tasks are not executed. Update time: January 9, 2019 09:34:57 Author: Hope on the field. This article mainly summarizes and introduces to you some reasons why crontab scheduled tasks are not executed. For everyone Solutions are given for each of the possible triggers, which have certain reference and learning value for colleagues who encounter this problem. Students in need can follow the editor to learn together. Preface: I have encountered some problems at work recently. The crontab scheduled task was not executed. Later, when I searched on the Internet, I found that the Internet mainly mentioned these five incentives: 1. The crond service is not started. Crontab is not a function of the Linux kernel, but relies on a cron.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles